package com.itheima.controller.backend.security;


import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
    @Autowired
    private UserService userService;;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User userByUsername = userService.findUserByUsername(username);
        if(Objects.isNull(userByUsername)){
            return null;
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
//        用户授权
        Set<Role> roles = userByUsername.getRoles();
        for (Role role : roles) {
            //遍历角色,授权所有用户
           authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
           Set<Permission> permissions = role.getPermissions();
           for (Permission permission : permissions) {
               //遍历权限，授权用户
               authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
           }
        }
        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(username,userByUsername.getPassword(),authorities);
        return securityUser;
    }
}
